import React from 'react';

import logo from '@/assets/logo.png';
import './index.scss';

import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import { useDispatch } from 'react-redux';

// import { useHistory } from 'react-router-dom';

import  {login}  from '@/store/actions/index'

import  { useHistory, useLocation }  from 'react-router-dom';


export default function Login() {
  const dispatch = useDispatch();
  const history = useHistory();
  const location= useLocation()

   // location 获取路由信息：地址  ?字符串  hash #符号后  state路由传值
     // 表单完成输入校验通过，触发的事件

  const onFinish = async (value) => {
    console.log('value',value)
     // 需要提交数据
    const { mobile, code } = value;
    try {
        // 进行登录
      await dispatch(login(mobile, code));
    
         message.success('登录成功')
         // history.replace('/home')
       // 跳转首页（如果有来源页面returnUrl就跳转这个地址）
       console.log( location)
       history.replace(location?.state?.returnUrl || '/home')
   
    } catch (e) {
      message.error(e.response?.data?.message || '登录失败');
    }
  };

  return (
    <div className="login">
      <div className="login-container">
        <img className="logon-logo" src={logo} alt="" />

        <Form
          size="large"
          validateTrigger={['onChange', 'onBlur']}
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            isAgree: true,
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机格式不正确',
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码6个字符串' },
            ]}
          >
            <Input prefix={<LockOutlined />} placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item name="isAgree" valuePropName="checked" rules={[]}>
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
